import { Component, toNative } from 'vue-facing-decorator'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FilterDto } from '@/render/FilterRender'
import type { AnyObject } from '@/types'
import { getKeyToEnum, InvoiceTypeCnEnum, InvoiceUploadStatusCnEnum } from '@/const/enum'
import PreviewPdf from '@/components/preview-media/PreviewPdf'
import PreivewImage from '@/components/preview-media/PreviewImage'
import DialogUpload from './components/DialogUpload'
import { exportInvoice, getInvoiceList, uploadInvoice, uploadInvoiceZip } from '@/api/invoice'
import type { InvoiceDto } from '@/api/invoice/types'
import { downloadFile, getCompanyListByName } from '@/utils/util'
import { getCompanyList } from '@/api/company'
import { Button, message, type UploadFile } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import { getSaleList } from '@/api/sale'
import { getSystemUserList } from '@/api/system'

@Component
export class NoUpload extends TableRender {
    showUploadZip = false
    showUpload = false

    uploadFile = null as File | null
    curItem = {} as InvoiceDto

    filterConfig() {
        return {
            companyName: {
                name: '客户名称',
                element: 'autoComplete',
                class: 'w-full',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            deptId: {
                name: '所属分组',
                element: 'select',
                optionsType: 'saleDept',
                callback: {
                    change: async (ev: number) => {
                        this.filters.salesId.value = ''
                        if (ev) {
                            this.filters.salesId.options = (
                                await getSystemUserList({
                                    deptId: ev,
                                    pageNum: 1,
                                    pageSize: 999
                                })
                            ).rows?.map((i) => {
                                return {
                                    label: i.nickName,
                                    value: i.userId
                                }
                            })
                        } else {
                            this.filters.salesId.options = (await getSaleList()).map((i) => {
                                return {
                                    label: i.saleName,
                                    value: i.saleId
                                }
                            })
                        }
                    }
                }
            },
            salesId: {
                name: '所属商务',
                element: 'select',
                optionsType: 'saleList'
            },
            status: {
                name: '发票状态',
                element: 'select',
                options: getKeyToEnum(InvoiceUploadStatusCnEnum)
            },
            applicationMonth: {
                name: '申请月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            month: {
                name: '发票月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            type: {
                name: '发票类型',
                element: 'select',
                options: getKeyToEnum(InvoiceTypeCnEnum)
            },
            openDay: {
                name: '开票月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },

            receiptIds: {
                name: '收款账户',
                element: 'select',
                multiple: true,
                params: {
                    maxTagCount: 1
                },
                optionsType: 'receipt',
                placeholder: '请选择（可多选）'
            }
            // companyName: {
            //     name: '申请公司名',
            //     element: 'select',
            //     remote: true,
            //     params: {
            //         method: async (val: string) => {
            //             const res = await getCompanyListByName(val)
            //             this.filters.companyName.options = res?.map(i => {
            //                 return {
            //                     label: i.label,
            //                     value: i.label
            //                 }
            //             })
            //         }
            //     }
            // },
        } as FilterDto
    }

    tableColumnConfigOld = () =>
        [
            {
                field: 'operate',
                title: '操作',
                width: 90,
                fixed: 'left',
                params: {
                    buttons: [
                        {
                            text: '上传',
                            event: (row: InvoiceDto) => {
                                this.onUpload(row)
                            }
                        }
                    ]
                },
                slots: {
                    default: 'buttons'
                }
            },
            {
                field: 'companyName',
                title: '客户名称',
                width: 200
            },
            {
                field: 'type',
                title: '发票类型',
                formatter: ({ row }) => {
                    return InvoiceTypeCnEnum[row.type]
                }
            },
            {
                field: 'month',
                title: '发票月份'
            },
            {
                field: 'applyTime',
                title: '申请时间',
                width: 150
            },
            {
                field: 'amount',
                title: '发票金额',
                slots: {
                    default: 'price'
                }
            },
            {
                field: 'rechargeAmount',
                title: '充值金额',
                slots: {
                    default: 'price'
                }
            },
            {
                field: 'salesName',
                title: '所属商务'
            },
            {
                field: 'bankName',
                title: '收款账户',
                width: 200
            }
        ] as TableRenderColumnTypes<InvoiceDto>

    onLoadData(page: number, size: number, filters: AnyObject) {
        filters.receiptIds = filters.receiptIds?.join(',') ?? ''
        return getInvoiceList({
            pageNum: page,
            pageSize: size,
            status: InvoiceUploadStatusCnEnum.未上传,
            ...filters
        })
    }

    onUploadZip() {
        this.showUploadZip = true
    }

    onUpload(row: InvoiceDto) {
        this.showUpload = true
        this.curItem = row
    }

    async onExport() {
        const params = this.getFilters()
        params.status = InvoiceUploadStatusCnEnum.未上传
        if (!params.applicationMonth) {
            message.warning('请先选择申请月份')
            return
        }
        const res = await exportInvoice(params)
        downloadFile(res)
    }

    async onConfirm(data: { file: UploadFile[]; close: () => void }, type: string) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const fileData = new FormData()
        fileData.append('file', data.file[0].originFileObj as File)
        if (type === 'zip') {
            await uploadInvoiceZip(fileData)
        } else {
            await uploadInvoice(fileData, this.curItem.id)
        }
        message.success('上传成功')
        this.reloadPage()
        data.close()
    }

    renderRightBtns() {
        return (
            <div class="flex gap-20px">
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onUploadZip}>
                    上传
                </Button>
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onExport}>
                    导出
                </Button>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                <DialogUpload
                    v-model:show={this.showUploadZip}
                    onConfirm={(event) => this.onConfirm(event, 'zip')}
                    accept=".zip"
                    v-slots={{
                        default: () => {
                            return (
                                <div class="text-sm text-black-200">
                                    {/* <div>
                                    上传文件名称格式：电子签__年-月.zip；如：电子签__2022-01.zip
                                </div> */}
                                    <div>
                                        上传文件名称格式：日日保__年-月.zip；如：日日保__2022-01.zip
                                    </div>
                                </div>
                            )
                        }
                    }}
                />

                <DialogUpload
                    v-model:show={this.showUpload}
                    onConfirm={(event) => this.onConfirm(event, 'single')}
                />
            </>
        )
    }
}

export default toNative(NoUpload)
